package cn.wolfcode.trip.admin.controller;

import cn.wolfcode.trip.base.domain.TravelCommend;
import cn.wolfcode.trip.base.query.TravelCommendQueryObject;
import cn.wolfcode.trip.base.service.ITravelCommendService;
import cn.wolfcode.trip.base.util.UploadUtil;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author by mycp
 * @Classname TravelCommendController
 * @Description TODO
 * @Date 2018/11/6 22:06
 */
@Controller
@RequestMapping("/travelCommend")
public class TravelCommendController {
    @Autowired
    private ITravelCommendService travelCommendService;

    /**
     * 分页查询
     * @param qo
     * @return
     */
    @RequestMapping("/list")
    public String list(@ModelAttribute("qo") TravelCommendQueryObject qo, Model model){
        // 根据推荐安排时间进行倒序查询
        qo.setOrderBy("schedule desc");
        PageInfo pageInfo = travelCommendService.query(qo);
        model.addAttribute("pageInfo", pageInfo);
        return "travelCommend/list";
    }

    @RequestMapping("/saveOrUpdate")
    public String saveOrUpdate(MultipartFile img, TravelCommend travelCommend){
        // 先判断前台是否有上传图片 且文件是否是图片格式
        // 定义文件上传文件的格式后缀名
        String fileType = "image";
        if (img != null && img.getContentType().startsWith(fileType)){
            // 先保存更新后的封面
            String coverUrl = UploadUtil.upload(img);
            // 将更改后的封面的url设置到travelCommend中替换掉旧的封面
            travelCommend.setCoverUrl(coverUrl);
        }
        travelCommendService.saveOrUpdate(travelCommend);
        // 重定向到游记推荐管理界面
        return "redirect:/travelCommend/list.do";
    }
}
